#!/bin/bash

# APS健康检查脚本
# 用于检查所有服务的运行状态

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}   APS系统健康检查${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 检查MySQL
echo -e "${YELLOW}检查MySQL...${NC}"
if docker exec aps-mysql mysqladmin ping -h localhost --silent 2>/dev/null; then
    echo -e "${GREEN}✓ MySQL运行正常${NC}"
    
    # 检查数据库连接数
    CONNECTIONS=$(docker exec aps-mysql mysql -uroot -p${MYSQL_ROOT_PASSWORD:-Jsyshiyou@0723} -e "SHOW STATUS LIKE 'Threads_connected';" --silent --skip-column-names 2>/dev/null | awk '{print $2}')
    echo -e "  当前连接数: ${CONNECTIONS}"
else
    echo -e "${RED}✗ MySQL未运行或连接失败${NC}"
fi
echo ""

# 检查Redis
echo -e "${YELLOW}检查Redis...${NC}"
if docker exec aps-redis redis-cli -a ${REDIS_PASSWORD:-123456} ping 2>/dev/null | grep -q "PONG"; then
    echo -e "${GREEN}✓ Redis运行正常${NC}"
    
    # 检查Redis内存使用
    MEMORY=$(docker exec aps-redis redis-cli -a ${REDIS_PASSWORD:-123456} INFO memory 2>/dev/null | grep "used_memory_human" | cut -d: -f2 | tr -d '\r')
    echo -e "  内存使用: ${MEMORY}"
else
    echo -e "${RED}✗ Redis未运行或连接失败${NC}"
fi
echo ""

# 检查后端服务
echo -e "${YELLOW}检查后端服务...${NC}"
BACKEND_HEALTH=$(curl -s http://localhost:8080/actuator/health 2>/dev/null)
if echo "$BACKEND_HEALTH" | grep -q '"status":"UP"'; then
    echo -e "${GREEN}✓ 后端服务运行正常${NC}"
    
    # 显示详细健康信息
    echo "$BACKEND_HEALTH" | grep -o '"[^"]*":"[^"]*"' | head -5
else
    echo -e "${RED}✗ 后端服务未运行或健康检查失败${NC}"
fi
echo ""

# 检查前端服务
echo -e "${YELLOW}检查前端服务...${NC}"
if curl -s -o /dev/null -w "%{http_code}" http://localhost 2>/dev/null | grep -q "200"; then
    echo -e "${GREEN}✓ 前端服务运行正常${NC}"
else
    echo -e "${RED}✗ 前端服务未运行或访问失败${NC}"
fi
echo ""

# 检查容器资源使用
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}   容器资源使用情况${NC}"
echo -e "${BLUE}========================================${NC}"
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}" 2>/dev/null

echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}   检查完成${NC}"
echo -e "${BLUE}========================================${NC}"

